package com.app.micaihu.view.main.game;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.comment.CommentResult;
import com.app.micaihu.bean.comment.NewsComment;
import com.app.micaihu.bean.infor.UserInfor;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.custom.components.ParamMap;
import com.app.micaihu.custom.view.MaxByteLengthEditText;
import com.app.micaihu.custom.view.MaxByteLengthEditTextWithoutEmoji;
import com.app.micaihu.custom.view.RatingBarView;
import com.app.micaihu.custom.view.dataview.MyExpressView;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.DialogUtils;
import com.app.micaihu.utils.HttpUtils;
import com.app.utils.util.ToastUtils;
import com.app.utils.util.ViewFrameUtils;
import com.app.utils.util.ViewSizeUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ViewUtils;
import com.google.gson.reflect.TypeToken;

import de.greenrobot.event.EventBus;


/**
 * Created by Guo on 2017/3/16.
 */

public class GameCommentActivity extends BaseOldActivity implements View.OnClickListener, View.OnFocusChangeListener, RatingBarView.OnRatingChangeListener, View.OnLayoutChangeListener, TextWatcher {
    /*****
     * 所有控件
     ****/
    private MaxByteLengthEditText mContentView;// 帖子内容
    //底部菜单相关控件
//    private GridView mPicGridView;// 图集
    private View mMenushowLayoutView;//详细菜单
    private MyExpressView mbq;// 米尔表情view
    private View bottomView;

    /****
     * 逻辑数据
     *****/
    private String mSendPostContent;//发表的内容
    private long clickTime = 0;//点击表情的当前时间  禁止连续点击表情过快
    private static final int MAX_CHAR = 600;
    private TextView tvSendPost;
    private HorizontalScrollView picContainer;
    private ImageView addPic;
    private LinearLayout llPicContainer;
    private MaxByteLengthEditTextWithoutEmoji mTitle;
    private View addbiaoqing;
    private String mSendPostTitle;
    private String gameId;
    private RatingBarView ratingBarView;
    private TextView tvPrompt;

    //星星标语
    private String[] starComment = {AppApplication.getInstance().getString(R.string.game_one_star),
            AppApplication.getInstance().getString(R.string.game_two_star),
            AppApplication.getInstance().getString(R.string.game_three_star),
            AppApplication.getInstance().getString(R.string.game_four_star),
            AppApplication.getInstance().getString(R.string.game_five_star)
    };
    private int i = 0;
    private int keyHeight;
//    private boolean canSendEnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addContentView(R.layout.activity_game_comment);
        getIntentData();
        initView();
        // 获取焦点 弹出键盘
        mContentView.setFocusable(true);
        mContentView.postDelayed(new Runnable() {
            @Override
            public void run() {
                KeyboardUtils.showSoftInput(mContentView);
                bottomView.setVisibility(View.VISIBLE);
                mContentView.requestFocus();//获取焦点 光标出现
            }
        },500);
    }


    /**************** 所有初始化的操作 start *********************/

    /**
     * 得到传输的数据
     */
    private void getIntentData() {
        Intent intent = getIntent();
        if (intent != null) {
            gameId = intent.getStringExtra(Config.Extra.PARAMETER1);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mMenushowLayoutView != null && mMenushowLayoutView.getVisibility() == View.VISIBLE) {
            //关闭底部菜单栏
            mMenushowLayoutView.setVisibility(View.GONE);
        }
    }


    /**
     * 初始化布局
     */
    private void initView() {
        setTitle(AppApplication.getInstance().getString(R.string.evaluate));
        /****内容控件相关  start***/
        mContentView = (MaxByteLengthEditText) findViewById(R.id.content);
        mContentView.setMaxByteLength(MAX_CHAR);
        mContentView.addTextChangedListener(this);
        mContentView.setOnClickListener(this);

        /****内容控件相关  end***/

        /*****底部菜单相关   start*****/
        //底部菜单栏
        bottomView = findViewById(R.id.includeBottom);
        //底部菜单内容
        mMenushowLayoutView = findViewById(R.id.menushowLayout);

        //添加表情按钮
        addbiaoqing = findViewById(R.id.iv_showbiaoqing);
        addbiaoqing.setOnClickListener(this);
        //发帖按钮
        tvSendPost = (TextView) findViewById(R.id.tv_send);
        tvSendPost.setOnClickListener(this);


        //配置表情显示的控件
        mbq = (MyExpressView) findViewById(R.id.biaoqingview);
        mbq.configView(mContentView, bottomView, 5, R.drawable.expression_yuandian, mActivity);

        //星星
        ratingBarView = (RatingBarView) findViewById(R.id.rbv_star);
        ratingBarView.setOnRatingChangeListener(this);


        tvPrompt = (TextView) findViewById(R.id.tv_prompt);


//        if(mContentView != null && TextUtils.isEmpty(mContentView.getText().toString().trim())
//                && i == 0){
//            tvSendPost.setEnabled(false);
//        }


        //监控 键盘
        //获取屏幕高度.监听键盘
        View rootActivity = findViewById(R.id.rl_activity);
        rootActivity.addOnLayoutChangeListener(this);
        int heightPixels = ViewSizeUtils.getHeightPixels();
        keyHeight = heightPixels / 3;


    }


    /****************
     * 所有初始化的操作 end
     *********************/


    /****************
     * 所有事件的操作 start
     *********************/


    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.content://标题、内容的单击事件
                showSoft();
                break;
            case R.id.tv_send:// 发表
//            case R.id.tv_page_header_function:
                sendComment();

                break;
            case R.id.iv_showbiaoqing://展示表情
                long time = System.currentTimeMillis();
                if (time - clickTime > 500) {
                    showBiaoqing();
                    clickTime = System.currentTimeMillis();
                }
                break;
            default:
                break;
        }
    }


    /**
     * 隐藏键盘和表情
     */
    private void hideSoftBiaoQin() {
        //关闭键盘
        ViewFrameUtils.closeInputSoft(mActivity, mContentView);
        //关闭表情
        if (mMenushowLayoutView != null) {
            mMenushowLayoutView.setVisibility(View.GONE);
        }

        if (mbq != null) {
            mbq.setVisibility(View.GONE);
        }

    }

    /**
     * 弹出键盘
     */
    private void showSoft() {
        if (mMenushowLayoutView != null) {
            mMenushowLayoutView.setVisibility(View.GONE);
        }

        if (mbq != null) {
            mbq.setVisibility(View.GONE);
        }

        if (bottomView != null && bottomView.getVisibility() == View.GONE) {
            bottomView.setVisibility(View.VISIBLE);
        }
        ViewFrameUtils.showSoftwareByView(mContentView);


        //测量键盘高度.为表情的height 赋值,只赋值一次
        if (bottomView == null || mMenushowLayoutView == null) {
            return;
        }

        if (bottomView.getTag() != null) {
            return;
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // 底部菜单内容版块(展示菜单的高度和键盘高度一样)
                int[] locations = new int[2];
                bottomView.getLocationOnScreen(locations);
                float viewOnHg = locations[1] + bottomView.getHeight();
                int screenHeight = ViewSizeUtils.getHeightPixels();
                int height = (int) (screenHeight - viewOnHg);
                mMenushowLayoutView.getLayoutParams().height = height;
                bottomView.setTag(true);// 代表已经初始化过高度就不在初始化了
            }
        }, 1000);
    }

    /**
     * 展示表情
     */
    private void showBiaoqing() {
        if (mMenushowLayoutView == null || mbq == null) {
            return;
        }
        //展示或隐藏表情
        if (mMenushowLayoutView.getVisibility() == View.VISIBLE && mbq.getVisibility() == View.VISIBLE) {
            mbq.showOrHideView();//此方法自带弹出键盘
            mMenushowLayoutView.setVisibility(View.GONE);
        } else {
            mbq.showOrHideView();
//			// 因为viewpager的显示要比键盘隐藏快，会导致UI体验不好，所以让viewpager的显示慢一点
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mMenushowLayoutView.setVisibility(View.VISIBLE);
                }
            }, 300);
        }
    }


    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (v.getId() == R.id.content && mbq != null) {
            mbq.setMsgEditView(mContentView);
        }
        //当exitView获取焦点时 弹出键盘 隐藏菜单
        if (hasFocus) {
            if (addbiaoqing != null) {
                addbiaoqing.setVisibility(View.VISIBLE);
            }
            showSoft();

        }

    }

    @Override
    public void onBackPressed() {
        if (mMenushowLayoutView != null && mMenushowLayoutView.getVisibility() == View.VISIBLE) {
            mMenushowLayoutView.setVisibility(View.GONE);
            bottomView.setVisibility(View.GONE);
            return;
        }
        super.onBackPressed();
        overridePendingTransition(0, R.anim.translate_slide_out_bottom);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //登录会来
        if (requestCode == UserInforManager.TO_LOGIN_REQUESTCODE && resultCode == RESULT_OK) {
            if (mContentView != null && !TextUtils.isEmpty(mContentView.getText().toString().trim())
                    && i > 0) {
                sendComment();
            }
        }

    }

    /**
     * 发表
     */
    private void sendComment() {
        if (mContentView == null) return;

        String commentMsg = mContentView.getText().toString().trim();


        if (!UserInforManager.getInstance().isLogin()) {
            //判断是否登陆
            UserInforManager.getInstance().toLoginPage(this.mActivity);
            return;
        } else if (TextUtils.isEmpty(commentMsg)) {
            ToastUtils.showText("评论内容不能为空");
            return;
        } else if (TextUtils.isEmpty(gameId)) {
            ToastUtils.showText("评论失败 , 请稍后再试");
            return;
        } else if (i == 0) {
            ToastUtils.showText("请打分");
            return;
        }

        UserInfor userinfo = UserInforManager.getInstance().getUserInfor();
        ParamMap paramMap = new ParamMap();
        paramMap.putEncode("uid", userinfo.getUid());
        paramMap.putEncode("articleId", gameId);
        paramMap.putEncode("content", commentMsg);
        paramMap.putEncode("type", "0");
        paramMap.putEncode("commentId", "");
        paramMap.putEncode("toUid", "");
        paramMap.putEncode("star", i + "");

        HttpUtils.ParmsMapMD5(paramMap);

        HttpListener<DataBean<CommentResult>> httpListener = new HttpListener<DataBean<CommentResult>>() {

            @Override
            public void onStart() {
                DialogUtils.getInstance().showProgressDialog(mActivity, "正在发表中...");

            }

            @Override
            public void onError(VolleyError error) {
                DialogUtils.getInstance().dismissProgressDialog();
                ToastUtils.showText(AppApplication.getInstance().getString(R.string.neterror));

            }

            @Override
            public void onSuccess(DataBean<CommentResult> response) {
                DialogUtils.getInstance().dismissProgressDialog();
                if (response.noError()) {
                    ToastUtils.makeText("发表成功");
                    hideSoftBiaoQin();
                    CommentResult data = response.getData();
                    NewsComment newsComment = data.toComment();
                    EventBus.getDefault().post(newsComment);
                    onBackPressed();
                } else {
                    ToastUtils.makeText(response.getMsg());
                }
            }
        };
        //请求网络
        addPostRequest(URIContant.NEWS_SENDCOMMENT, new TypeToken<DataBean<CommentResult>>() {
        }.getType(), paramMap, httpListener);


    }

    @Override
    public void onRatingChange(float RatingCount) {
        if (tvPrompt != null && mContentView != null && tvSendPost != null) {
            i = (int) RatingCount;
            tvPrompt.setText(starComment[i - 1]);
//            canSendEnable = true;
//            if(!TextUtils.isEmpty(mContentView.getText().toString().trim())){
//                tvSendPost.setEnabled(true);
//            }else{
//                tvSendPost.setEnabled(false);
//            }

        }
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {//弹起
        } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {//关闭
            if (mbq.getVisibility() == View.GONE) {
                bottomView.setVisibility(View.GONE);
            }

        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
//        if(mContentView != null && tvSendPost != null){
//            if(!TextUtils.isEmpty(mContentView.getText().toString().trim())
//                    && canSendEnable){
//                tvSendPost.setEnabled(true);
//            }else{
//                tvSendPost.setEnabled(false);
//            }
//        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
